package san.java.day10;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Collection工具类:  类似于C++中的algorithm头文件
 *  Collection中常用的方法:
 *      1. reverse(List)
 *      2. shuffle(List)
 *      3. sort(List)
            sort(List, Comparator)
 *      4. swap(List, int, int)
 *      5. max/min(List)
 *          max/min(List, Comparator)
 *      6. frequency(List, element)
 *      7. replaceAll(List, oldVal, newVal): 使用新值替换List对象的所有旧值
 *
 *  Collection中的同步控制:  只做了解
 *      Collection类中提供了多个synchronizedXxx()方法,该方法可使将指定集合包装成线程同步的集合,
 *      从而解决出现的线程安全问题.
 */

public class Collection_08 {
    public static void main(String[] args) {
        List<String> sList = new ArrayList<String>();
        sList.add("b");
        sList.add("a");
        sList.add("f");
        sList.add("e");
        sList.add("g");

        System.out.println(sList);

        // 反转
        Collections.reverse(sList);
        System.out.println(sList);

        // 乱序
        Collections.shuffle(sList);
        System.out.println(sList);

        // sort: 排序
        Collections.sort(sList);
        System.out.println(sList);

        List<Student> stuList = new ArrayList<Student>();
        Student s1 = new Student(1, "san");
        Student s2 = new Student(5, "wangwu");
        Student s3 = new Student(4, "lisi");
        stuList.add(s1);
        stuList.add(s2);
        stuList.add(s3);
        System.out.println(stuList);

        Collections.sort(stuList);
        System.out.println(stuList);

        // swap
        Collections.swap(sList, 0, 2);
        System.out.println(sList);

        // max, min
        System.out.println(Collections.max(sList));
        System.out.println(Collections.min(sList));

        // frequency
        sList.add("a");
        System.out.println(Collections.frequency(sList, "a"));

        //replaceAll
        boolean flag = Collections.replaceAll(sList, "a", "na");
        System.out.println(sList);

    }
}

class Student implements Comparable<Student> {

    int id;
    String name;

    public Student() {

    }

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        if (this.id > o.id)
            return 1;
        else if (this.id < o.id)
            return -1;
        return 0;
    }
}
